<template>
  <div class="todo-detail-page">
    <div class="page-header">
      <el-button :icon="ArrowLeft" @click="handleBack" type="text" size="large"/>

      <h1 class="page-title">{{ todo?.title || '待办详情' }}</h1>

      <div class="header-right" v-if="todo">
        <el-button :icon="Edit" @click="handleEdit" type="primary" circle/>

        <el-button :icon="Delete" @click="handleDelete" type="danger" plain circle/>
      </div>
    </div>

    <div class="detail-container" v-loading="loading">
      <div v-if="!todo && !loading" class="error-state">
        <el-result icon="warning" title="待办事项不存在" sub-title="请检查链接是否正确，或该待办事项已被删除">
          <template #extra>
            <el-button type="primary" @click="handleBack">返回列表</el-button>
          </template>
        </el-result>
      </div>

      <div v-else-if="todo" class="todo-content">
        <!-- 基本信息 -->
        <div class="info-section">
          <div class="section-header">
            <div class="title-row">
              <div style="display: flex; gap: 0.5rem; align-items: center; font-size: 0.7rem;">
                <el-icon>
                  <Calendar/>
                </el-icon>

                <span class="meta-value">{{ todo.createdTime }}</span>
              </div>

              <div class="status-badges">
                <el-tag
                    :type="getStatusType(todo.status)"
                    size="large"
                    class="status-tag"
                >
                  {{ getStatusLabel(todo.status) }}
                </el-tag>
                <el-tag
                    :type="getPriorityType(todo.priority)"
                    size="large"
                    class="priority-tag"
                >
                  {{ getPriorityLabel(todo.priority) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 待办内容 -->
        <div class="info-section" v-if="todo.content">
          <MarkdownRenderer :content="todo.content" theme="classic" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  ArrowLeft,
  Edit,
  Delete,
  Calendar,
} from '@element-plus/icons-vue'
import type {TodoItem} from '../types'
import {TodoStatus, TodoPriority} from '../types'
import {todoApi} from '../api'
import {useTodos} from '../composables'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

const router = useRouter()
const route = useRoute()

// 使用待办事项管理
const {
  deleteTodo,
  loadCategories
} = useTodos()

// 状态
const loading = ref(true)
const todo = ref<TodoItem | null>(null)
const todoId = ref<string>('')


// 加载待办详情
const loadTodoDetail = async (id: string) => {
  try {
    loading.value = true
    const todoData = await todoApi.getById(id)
    todo.value = todoData
  } catch (error) {
    ElMessage.error('加载待办详情失败：' + (error as Error).message)
    todo.value = null
  } finally {
    loading.value = false
  }
}

// 处理返回
const handleBack = () => {
  // 保持当前的查询参数，特别是categoryId
  router.push({
    path: '/todo',
    query: route.query  // 保持当前所有查询参数
  })
}

// 处理编辑
const handleEdit = () => {
  if (todo.value) {
    router.push({
      path: `/todo/edit/${todo.value.id}`,
      query: route.query  // 保持当前所有查询参数
    })
  }
}

// 处理删除
const handleDelete = async () => {
  if (!todo.value) return

  try {
    await ElMessageBox.confirm(
        '确定要删除这个待办事项吗？删除后无法恢复。',
        '确认删除',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    await deleteTodo(todo.value.id)
    ElMessage.success('删除成功')
    router.push({
      path: '/todo',
      query: route.query  // 保持当前所有查询参数
    })
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error as Error).message)
    }
  }
}

// 获取状态类型
const getStatusType = (status: TodoStatus) => {
  switch (status) {
    case TodoStatus.TODO:
      return 'info'
    case TodoStatus.IN_PROGRESS:
      return 'warning'
    case TodoStatus.COMPLETED:
      return 'success'
    case TodoStatus.CANCELLED:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态标签
const getStatusLabel = (status: TodoStatus) => {
  switch (status) {
    case TodoStatus.TODO:
      return '待处理'
    case TodoStatus.IN_PROGRESS:
      return '进行中'
    case TodoStatus.COMPLETED:
      return '已完成'
    case TodoStatus.CANCELLED:
      return '已取消'
    default:
      return '未知'
  }
}

// 获取优先级类型
const getPriorityType = (priority: TodoPriority) => {
  switch (priority) {
    case TodoPriority.URGENT:
      return 'danger'
    case TodoPriority.HIGH:
      return 'warning'
    case TodoPriority.MEDIUM:
      return 'primary'
    case TodoPriority.LOW:
      return 'info'
    default:
      return 'info'
  }
}

// 获取优先级标签
const getPriorityLabel = (priority: TodoPriority) => {
  switch (priority) {
    case TodoPriority.URGENT:
      return '紧急'
    case TodoPriority.HIGH:
      return '高'
    case TodoPriority.MEDIUM:
      return '中'
    case TodoPriority.LOW:
      return '低'
    default:
      return '未知'
  }
}


// 页面初始化
onMounted(async () => {
  // 获取路由参数中的ID
  const id = route.params.id as string
  if (!id) {
    ElMessage.error('无效的待办事项ID')
    router.push({
      path: '/todo',
      query: route.query  // 保持当前所有查询参数
    })
    return
  }

  todoId.value = id

  // 并行加载分类和待办详情
  await Promise.all([
    loadCategories(),
    loadTodoDetail(id)
  ])
})
</script>

<style scoped>
.todo-detail-page {
  padding: 1rem;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.header-right {
  display: flex;
  align-items: center;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
  flex: 1;
  text-align: center;
}

.detail-container {
  overflow: hidden;
}

.error-state {
  padding: 60px 20px;
}

.todo-content {
  padding: 0;
}

.info-section:last-child {
  border-bottom: none;
}

.section-header {
  margin-bottom: 16px;
}

.title-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.status-badges {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.status-tag,
.priority-tag {
  font-weight: 500;
}

.meta-value {
  color: var(--el-text-color-primary);
}

.meta-value.overdue {
  color: var(--el-color-danger);
  font-weight: 500;
}

.description-text {
  font-size: 16px;
  line-height: 1.6;
  color: var(--el-text-color-primary);
  white-space: pre-wrap;
  word-break: break-word;
}


@media (max-width: 768px) {
  .todo-detail-page {
    padding: 16px;
  }

  .detail-container {
    margin: 0;
  }

  .title-row {
    flex-direction: column;
    gap: 12px;
  }

  .page-title {
    font-size: 20px;
  }

  .header-right {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .category-display {
    padding: 10px 12px;
  }

  .description-text {
    padding: 16px;
    font-size: 15px;
  }

  .section-title {
    font-size: 16px;
  }
}
</style>